package wh.二叉树的中序遍历;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2022/3/31 21:10
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(2,new TreeNode(4),new TreeNode(3));
        TreeNode root = new TreeNode(1,node1,new TreeNode(5));
        List<Integer> integers = inorderTraversal(root);
        System.out.println(integers);
    }

    //解法1:递归解法
    public static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        inorder(root, res);
        return res;
    }
    public static void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }

    //解法2:迭代解法，使用栈来保存中间数据 （两种方式是等价的，区别在于递归的时候隐式地维护了一个栈，而我们在迭代的时候需要显式地将这个栈模拟出来）
    public static List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        //定义了一个栈用来存储二叉树节点
        Deque<TreeNode> stk = new LinkedList<TreeNode>();
        while (root != null || !stk.isEmpty()) {
            while (root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}
